import { useNavigate } from "react-router-dom";
import PubSub from "pubsub-js";
import "@/assets/styles/Login.scss";
import { useState } from "react";
import sha256 from "crypto-js/sha256";
import url from "@/configs/server";
import { message } from "antd";

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  localStorage.removeItem('refresh_token')
  localStorage.removeItem('login_token')

  const navigateTo = useNavigate();

  const toRegister = () => {
    PubSub.publish("ChangeMenu", "/register");
    navigateTo("/register");
  };

  const login = async (e: any) => {
    e.preventDefault();
    const m = sha256(password).toString();
    try {
      const response = await fetch(url.URL + `/user/login`, {
        method: "POST",
        body: JSON.stringify({
          username: username,
          password: m,
        }),
      });
      const data = await response.json();
      switch (data.code) {
        case 1006:
          message.open({
            type: "error",
            content: "用户名不存在！",
          });
          break;
        case 1007:
          message.open({
            type: "error",
            content: "密码错误",
          });
          break;
        case 2001:
          PubSub.publish("freshMenu");
          PubSub.publish("ChangeMenu", data.to);
          localStorage.setItem('login_token',data.login_token)
          localStorage.setItem('refresh_token',data.refresh_token)
          navigateTo(data.to);
          break;
        default:
          message.open({
            type: "warning",
            content: "未知错误",
          });
          break;
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="Container">
      <div className="box">
        <form className="login_form">
          <h2>登陆</h2>
          <div className="inputBox">
            <input
              type="text"
              required
              onBlur={(e: any) => setUsername(e.target.value)}
            />
            <span>账号</span>
            <i />
          </div>
          <div className="inputBox">
            <input
              type="password"
              required
              onBlur={(e: any) => setPassword(e.target.value)}
            />
            <span>密码</span>
            <i />
          </div>
          <div className="links">
            <a href="#">忘记密码？</a>
            <a onClick={toRegister}>注册</a>
          </div>
          <input type="submit" onClick={login} value="登陆" />
        </form>
      </div>
    </div>
  );
}
